package util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * md5工具类
 *
 * @date 2022/4/11
 * */
public class MD5Util {

    final static private String algorithm = "MD5";
    final static private char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();

    public static void main(String[] args){
        String password = "123456";
        String encrypt = encrypt(password);
        System.out.println(encrypt);
        System.out.println(isMatcher(password, encrypt));
    }

    /**
     * 判断加密后的数字和原密码是否匹配
     * @param password 原密码
     * @param encryptPassword 加密密码
     * @return true：密码匹配，false：密码不匹配
     * */
    public static boolean isMatcher(String password, String encryptPassword) {
        String encrypt = encrypt(password);
        return encrypt.equals(encryptPassword);
    }

    /**
     * 加密
     * @param password 加密验证
     * @return 加密以后的字符串
     * */
    public static String encrypt(String password) {
        String passwordMd5 = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance(algorithm);
            byte[] bytes = md5.digest(password.getBytes(StandardCharsets.UTF_8));
            passwordMd5 = toHex(bytes);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return passwordMd5;
    }

    /**
     * 字节转为16进制字符串
     * @param bytes 加密字节
     * */
    private static String toHex(byte[] bytes) {
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (byte aByte : bytes) {
            ret.append(HEX_DIGITS[(aByte >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[aByte & 0x0f]);
        }
        return ret.toString();
    }
}
